import { useState, useEffect } from 'react'
import { Input, Modal } from 'antd'
import { FormOutlined } from '@ant-design/icons'
import PropTypes from 'prop-types'
import { queryList } from '../../apis/formDefinition'
import useQueryList from '../../hooks/useQueryList'
import useModeler from '../../hooks/useModeler'
import CommonTable from "../common/CommonTable"

const InputFormPicker = ({
  value = {},
  onChange
}) => {
  const [visible, setVisible] = useState(false)

  const handleShow = () => {
    setVisible(true)
  }

  const handleCancel = () => {
    setSelectedRowKeys([])
    setVisible(false)
  }

  const handleConfirm = () => {
    if (selectedRowKeys && selectedRowKeys.length > 0) {
      const newValue = listData.find(el => el.id === selectedRowKeys[0])
      onChange({
        id: newValue.id,
        key: newValue.key,
        name: newValue.name
      })
      handleCancel()
    }
  }

  const {
    listData,
    loading,
    doQueryList,
    selectedRowKeys,
    setSelectedRowKeys,
    rowSelection
  } = useQueryList({
    apis: { queryList },
    isAutoQuery: false,
    moduleName: '表单'
  })

  const {
    commonSetting
  } = useModeler({
    modelType: 2,
    doQueryList
  })

  useEffect(() => {
    if (visible) {
      doQueryList()
    }
  }, [visible])

  return <>
    <Input
      onClick={handleShow}
      readOnly
      value={value.name}
      addonBefore={<FormOutlined />}
    />
    <Modal
      title="表单引用"
      visible={visible}
      onCancel={handleCancel}
      maskClosable={false}
      keyboard={false}
      onOk={handleConfirm}
      width={888}
      okButtonProps={{
        disabled: selectedRowKeys.length === 0
      }}
    >
      <div
        style={{
          maxHeight: 500,
          overflow: 'auto'
        }}
      >
        <CommonTable
          loading={loading}
          dataSource={listData}
          columns={commonSetting.modelerListColumns}
          rowSelection={{
            ...rowSelection,
            type: 'radio',
            getCheckboxProps: (rowData) => {
              return {
                disabled: rowData.id === value.id
              }
            }
          }}
          onRow={(rowData) => ({
            onClick: () => {
              setSelectedRowKeys([rowData.id])
            }
          })}
        ></CommonTable>
      </div>
    </Modal>
  </>
}

InputFormPicker.propTypes = {
  value: PropTypes.any,
  onChange: PropTypes.func
}

InputFormPicker.propsMap = []

export default InputFormPicker